package com.example.myapplication

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.myapplication.common.AbstractFragment
import com.example.myapplication.ui.account.LoginFragment
import com.example.myapplication.work.WorkerFragment
/**
 * 基础的Activity
 */
class FileActivity : AppCompatActivity() {

    private val loginFragment = LoginFragment()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file)
        loadFragment(loginFragment, true)
        //loadFragment(WorkerFragment(), true)
    }

    /**
     * 加载一个fragment
     */
    fun loadFragment(
        fragment: Fragment,
        addToBackStack: Boolean
    ) {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction =
            fragmentManager.beginTransaction()
        val fragmentById =
            fragmentManager.findFragmentById(getFrameLayoutId())
        if (fragmentById == null) {
            fragmentTransaction.add(getFrameLayoutId(), fragment, fragment.javaClass.name)
        } else {
            fragmentTransaction.replace(getFrameLayoutId(), fragment, fragment.javaClass.name)
        }
        if (addToBackStack) {
            fragmentTransaction.addToBackStack(fragment.javaClass.name)
        }
        fragmentTransaction.commit()
    }

    private fun getFrameLayoutId(): Int {
        return R.id.frag_layout
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        supportFragmentManager.fragments.forEach {
            it.onActivityResult(requestCode, resultCode, data)
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onStart() {
        super.onStart()
        AppManager.getInstance().onActivityVisible(this)
    }

    override fun onStop() {
        AppManager.getInstance().onActivityNotVisible(this)
        super.onStop()
    }

    override fun onBackPressed() {
        val fragmentManager = supportFragmentManager
        var fragment = fragmentManager.findFragmentById(getFrameLayoutId())
        if (fragment is AbstractFragment) {
            if (fragment.onBackPressed()) {
                return
            }
        }
        super.onBackPressed()
        fragment = fragmentManager.findFragmentById(getFrameLayoutId())
        if (fragment == null) {
            finish()
        }
    }

}